'use client';

import type { ISectionGroup } from '@/interfaces';
import classNames from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { HomeH5PageContext } from '@/contexts/mobile/home';
import Link from 'next/link';
import { generateRandomLinearGradientColor } from '@/lib/tool';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export default function SectionGroupHomeH5Page(
  this: any,
  {
    items = [],
  }: {
    items?: ISectionGroup[];
  },
) {
  const context = useContext(HomeH5PageContext);
  const [cardBackgroundColor, setCardBackgroundColor] = useState<string[]>([]);

  useEffect(() => {
    setCardBackgroundColor(
      items.map((_) => generateRandomLinearGradientColor()),
    );
  }, [items]);

  function onClickItem(item: ISectionGroup) {
    const _currentSectionGroupItem =
      context.currentSectionGroupItem &&
      context.currentSectionGroupItem.id === item.id
        ? undefined
        : item;
    if (typeof context.setCurrentSectionGroupItem === 'function') {
      context.setCurrentSectionGroupItem(_currentSectionGroupItem);
    }
  }

  return (
    <div className="vstack gap-3">
      <div className="hstack gap-4 align-items-center justify-content-between">
        <div className="h4 mb-0">相关内容</div>
        <Link
          className={classNames(
            'text-decoration-none',
            items.length === 0 ? 'text-muted' : 'text-reset',
          )}
          href="/sections"
        >
          更多<i className="bi bi-chevron-right"></i>
        </Link>
      </div>
      <div className="pb-2 hstack gap-4 flex-nowrap text-nowrap overflow-x-auto">
        {items.map((item, index) => {
          if (
            cardBackgroundColor.length > 0 &&
            context.currentSectionGroupItem &&
            context.currentSectionGroupItem.id === item.id
          ) {
            return (
              <div
                key={item.id}
                onClick={onClickItem.bind(this, item)}
                className="rounded-4 flex-shrink-0 d-flex justify-content-center align-items-center cursor-pointer"
                style={{
                  width: 260,
                  height: 146,
                  background: cardBackgroundColor[index],
                  mixBlendMode: 'difference',
                }}
              >
                {item.name}
              </div>
            );
          } else {
            return (
              <div
                key={item.id}
                onClick={onClickItem.bind(this, item)}
                className="rounded-4 bg-light flex-shrink-0 d-flex justify-content-center align-items-center cursor-pointer"
                style={{
                  width: 260,
                  height: 146,
                }}
              >
                {item.name}
              </div>
            );
          }
        })}
      </div>
      {items.length === 0 && <Nodata />}
    </div>
  );
}
